package com.freedy.dataStructure.queue;

/**
 * @author Freedy
 * @date 2021/3/14 12:46
 */
public class ArrQueue {
    public static void main(String[] args) {
        //测试
        CircleQueue queue = new CircleQueue(3);

        queue.addQueue(1);
        queue.addQueue(2);
        queue.addQueue(3);
        queue.popQueue();
        queue.popQueue();
        queue.addQueue(41);
        queue.addQueue(51);
        queue.popQueue();
        queue.addQueue(51);
        queue.popQueue();
        queue.popQueue();


        System.out.println(queue.size());
        queue.showQueue();

    }
}

/**
 * 使用数组模拟队列
 * 队列类
 */
class CircleQueue{
    private int maxSize;//表示数组最大容量
    private int front;//指向队列头部的前一个位置
    private int rear;//指向队列尾具体位置
    private int[] arr;//该数组用于存放数据

    //构造队列
    public CircleQueue(int maxSize){
        this.maxSize=maxSize+1;
        arr=new int[this.maxSize];
        front=0;
        rear=0;
    }

    //判断队列是否满
    public boolean isFull(){
        return (rear+1)%maxSize==front;
    }

    //判断队列是否为空
    public boolean isEmpty(){
        return rear==front;
    }

    //添加数据到队列
    public void addQueue(int n){
        if (isFull()){
            throw new RuntimeException("队列已满,不能加入数据！");
        }
        arr[rear]=n;
        rear=(rear+1)%maxSize;//rear后移
    }

    //取数据
    public int popQueue(){
        if (isEmpty()){
            throw new RuntimeException("队列为空！");
        }
        int ret=arr[front];
        front=(front+1)%maxSize;
        return ret;
    }

    public void showQueue(){
        if (isEmpty()){
            throw new RuntimeException("队列为空！");
        }
        for (int i = 0; i < size(); i++) {
            System.out.print(arr[(front+i)%maxSize]);
        }
    }

    //显示队列的头（不取数据）
    public int peek(){
        if (isEmpty()){
            throw new RuntimeException("队列为空！");
        }
        return arr[front];
    }

    //求队列长度
    public int size(){
       return (rear + maxSize - front)% maxSize;
    }

}
